<?php

namespace app\common\model\business;

use think\Model;

// 引入软删除模型
use traits\model\SoftDelete;

class Business extends Model
{

    // 调用软删除模型
    use SoftDelete;

    // 指定的数据表
    protected $name = 'business';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义创建时间字段
    protected $createTime = 'createtime';

    // 定义更新时间字段 => false 禁用
    protected $updateTime = false;

    // 定义软删除字段
    protected $deleteTime = 'deletetime';

    // 定义数据表不存在的字段
    protected $append = [
        'avatar_cdn',
        'createtime_text',
        'region_text',
        'gender_text'
    ];


    /**
     * 头像获取器
     * @param string $value 当前字段名的值
     * @param array $data 当前数据
     */
    public function getAvatarCdnAttr($value, $data)
    {
        $avatar = !empty($data['avatar']) ? $data['avatar'] : '';

        // 获取当前域名
        $domain = request()->domain();

        if (empty($avatar) || !is_file('.' . $avatar)) {
            return $domain . '/assets/img/avatar.png';
        }

        return $domain . $avatar;
    }

    public function getCreateTimeTextAttr($value, $data)
    {

        $createTime = empty($data['createtime']) ? '' : $data['createtime'];

        if (empty($createTime)) {
            return '未知时间';
        }

        return date('Y-m-d', $createTime);
    }

    public function admin()
    {
        return $this->belongsTo('app\common\model\admin\Admin', 'adminid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getRegionTextAttr($value, $data)
    {
        // 区划码
        $province = $data['province'] ?? '';
        $city = $data['city'] ?? '';
        $district = $data['district'] ?? '';

        // 查询地区表
        $provinceName = model('Region')->where(['code' => $province])->value('name');
        $cityName = model('Region')->where(['code' => $city])->value('name');
        $districtName = model('Region')->where(['code' => $district])->value('name');

        $regionText = '';

        if (!empty($provinceName)) {
            $regionText .= $provinceName . '-';
        }

        if (!empty($cityName)) {
            $regionText .= $cityName . '-';
        }

        if (!empty($districtName)) {
            $regionText .= $districtName;
        }

        return $regionText ?: '未知地区';
    }

    public function getGenderList()
    {
        return [
            0 => '保密',
            1 => '男',
            2 => '女'
        ];
    }

    public function getGenderTextAttr($value, $data)
    {
        $gender = $data['gender'] ?: 0;

        return $this->getGenderList()[$gender];
    }
}
